﻿using ACadSharp.Tables;
using ArcGIS.Core.CIM;
using ArcGIS.Desktop.Core;
using ArcGIS.Desktop.Framework.Threading.Tasks;
using ArcGIS.Desktop.Layouts;
using ArcGIS.Desktop.Mapping;
using Aspose.Cells;
using CCTool.Scripts.Manager;
using CCTool.Scripts.ToolManagers;
using CCTool.Scripts.ToolManagers.Extensions;
using CCTool.Scripts.ToolManagers.Managers;
using NPOI.OpenXmlFormats.Dml.Chart;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace CCTool.Scripts.MixApp.StyleMix
{
    /// <summary>
    /// Interaction logic for ExportItem.xaml
    /// </summary>
    public partial class ExportItem : ArcGIS.Desktop.Framework.Controls.ProWindow
    {
        // 工具设置标签
        readonly string toolSet = "ExportItem";

        public ExportItem()
        {
            InitializeComponent();
            Init();
        }

        // 定义一个进度框
        private ProcessWindow processwindow = null;
        string tool_name = "导出工程要素";


        // 初始化窗体
        private void Init()
        {
            // 初始化参数选项
            textOutputPath.Text = BaseTool.ReadValueFromReg(toolSet, "outputPath", "");

            // 可选项参数
            cb_layout.IsChecked = BaseTool.ReadValueFromReg(toolSet, "IsLayout", "true").ToBool();
            cb_map.IsChecked = BaseTool.ReadValueFromReg(toolSet, "IsMap", "true").ToBool();
            cb_layer.IsChecked = BaseTool.ReadValueFromReg(toolSet, "IsLayer", "true").ToBool();
            cb_stylx.IsChecked = BaseTool.ReadValueFromReg(toolSet, "IsStylx", "true").ToBool();
        }


        private void openOutputButton_Click(object sender, RoutedEventArgs e)
        {
            textOutputPath.Text = UITool.OpenDialogFolder();
        }

        private async void btn_go_click(object sender, RoutedEventArgs e)
        {
            try
            {
                // 获取参数
                string outputPath = textOutputPath.Text;
                bool IsLayout = (bool)cb_layout.IsChecked;
                bool IsMap = (bool)cb_map.IsChecked;
                bool IsLayer = (bool)cb_layer.IsChecked;
                bool IsStylx = (bool)cb_stylx.IsChecked;

                // 写入本地
                BaseTool.WriteValueToReg(toolSet, "outputPath", outputPath);

                BaseTool.WriteValueToReg(toolSet, "IsLayout", IsLayout);
                BaseTool.WriteValueToReg(toolSet, "IsMap", IsMap);
                BaseTool.WriteValueToReg(toolSet, "IsLayer", IsLayer);
                BaseTool.WriteValueToReg(toolSet, "IsStylx", IsStylx);


                Close();

                // 打开进度框
                ProcessWindow pw = UITool.OpenProcessWindow(processwindow, tool_name);
                pw.AddMessageTitle(tool_name);

                await QueuedTask.Run(() =>
                {
                    pw.AddMessageStart( "创建目标文件夹");
                    string projectName = Project.Current.Name.Replace(".aprx", "");
                    // 创建文件夹
                    DirTool.CreateFolder($@"{outputPath}\{projectName}");
                    
                    // 布局
                    if (IsLayout)
                    {
                        pw.AddMessageMiddle(20, "导出布局");
                        // 创建文件夹
                        string folder = $@"{outputPath}\{projectName}\布局";
                        DirTool.CreateFolder(folder);
                        
                        var layoutItemList = Project.Current.GetItems<LayoutProjectItem>();
                        foreach (var layoutItem in layoutItemList)
                        {
                            pw.AddMessageMiddle(0, $"     {layoutItem.Name}", Brushes.Gray);

                            Layout layout = layoutItem.GetLayout();
                            layout.SaveAsFile($@"{folder}\{layout.Name}.pagx", true);
                        }
                    }

                    // 地图
                    if (IsMap)
                    {
                        pw.AddMessageMiddle(20, "导出地图");
                        // 创建文件夹
                        string folder = $@"{outputPath}\{projectName}\地图";
                        DirTool.CreateFolder(folder);

                        var mapItemList = Project.Current.GetItems<MapProjectItem>();
                        foreach (var mapItem in mapItemList)
                        {
                            pw.AddMessageMiddle(0, $"     {mapItem.Name}", Brushes.Gray);

                            Map map = mapItem.GetMap();
                            map.SaveAsFile($@"{folder}\{map.Name}.mapx", true);
                        }
                    }

                    // 图层
                    if (IsLayer)
                    {
                        pw.AddMessageMiddle(20, "导出图层");
                        // 创建文件夹
                        string folder = $@"{outputPath}\{projectName}\图层";
                        DirTool.CreateFolder(folder);
                        // 获取图层
                        Map map = MapView.Active.Map;
                        if (map is null)
                        {
                            return;
                        }
                        Dictionary<FeatureLayer, string> featureLayers = map.AllFeatureLayersDic();

                        foreach (var featureLayer in featureLayers)
                        {
                            string newName = featureLayer.Value.Replace(@"\", "_");

                            pw.AddMessageMiddle(0, $"     {newName}", Brushes.Gray);

                            // 创建LayerDocument并保存为.lyrx文件
                            LayerDocument layerDocument = new LayerDocument(featureLayer.Key);
                            layerDocument.Save(@$"{folder}\{newName}.lyrx");  // 指定保存路径
                        }
                    }

                    // 样式库
                    if (IsStylx)
                    {
                        pw.AddMessageMiddle(20, "导出样式库");
                        // 创建文件夹
                        string folder = $@"{outputPath}\{projectName}\样式库";
                        DirTool.CreateFolder(folder);

                        var stylxItemList = Project.Current.GetItems<StyleProjectItem>();
                        foreach (var stylxItem in stylxItemList)
                        {
                            var sourcePath = stylxItem.Path;
                            if (!sourcePath.Contains(@"\"))
                            {
                                continue;
                            }

                            pw.AddMessageMiddle(0, $"     {stylxItem.Name}", Brushes.Gray);
                            File.Copy(sourcePath, $@"{folder}\{stylxItem.Name}.style", true);
                        }
                    }

                });

                pw.AddMessageEnd();

            }
            catch (Exception ee)
            {
                MessageBox.Show(ee.Message + ee.StackTrace);
                return;
            }
        }

        private void btn_help_Click(object sender, RoutedEventArgs e)
        {
            string url = "https://blog.csdn.net/xcc34452366/article/details/152809315";
            UITool.Link2Web(url);
        }
    }
}
